package main

import (
	"log"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/redis"
	"github.com/gin-gonic/gin"

	"webcppcluster/cache"
	"webcppcluster/config"
	"webcppcluster/handlers"
)

func main() {
	// 初始化配置
	if err := config.InitDB(); err != nil {
		log.Fatalf("Failed to initialize database: %v", err)
	}
	defer config.Close()

	config.InitRedis()

	// 初始化Redis Session存储
	// redis.NewStore参数：size, network, address, password, keyPairs
	store, err := redis.NewStore(10, "tcp", 
		config.RedisHost+":6379", config.RedisPassword, []byte("secret"))
	if err != nil {
		log.Fatalf("Failed to initialize redis session store: %v", err)
	}

	// 创建应用Redis存储（用于业务逻辑）
	redisStore := cache.NewRedisStore(config.SessionExpireTime)

	// 初始化处理器
	handlers.Init(redisStore)

	// 创建Gin路由器
	r := gin.Default()

	// 配置Session中间件
	r.Use(sessions.Sessions("mysession", store))

	// 路由配置
	r.GET("/", handlers.Hello)
	r.POST("/register", handlers.Register)
	r.POST("/login", handlers.Login)
	r.GET("/shop/cfg", handlers.CheckLoginMiddleware(), handlers.Shopcfg)
	r.POST("/shop/buy", handlers.CheckLoginMiddleware(), handlers.Shopbuy)
	r.GET("/task/cfg", handlers.CheckLoginMiddleware(), handlers.Taskcfg)
	r.POST("/task/reward", handlers.CheckLoginMiddleware(), handlers.Taskreward)
	r.POST("/sign", handlers.CheckLoginMiddleware(), handlers.Sign)
	r.POST("/mail/send", handlers.Mailsend)
	r.GET("/mail/list", handlers.CheckLoginMiddleware(), handlers.Maillist)

	// 启动服务器
	log.Println("Server starting on :8085")
	if err := r.Run(":8085"); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}


